package com.leicx.guli.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leicx.guli.common.constant.ParamConstant;
import com.leicx.guli.common.utils.CommonPageQueryUtil;
import com.leicx.guli.common.utils.PageUtils;
import com.leicx.guli.common.utils.Query;
import com.leicx.guli.product.dao.AttrDao;
import com.leicx.guli.product.entity.AttrAttrgroupRelationEntity;
import com.leicx.guli.product.entity.AttrEntity;
import com.leicx.guli.product.entity.AttrGroupEntity;
import com.leicx.guli.product.entity.CategoryEntity;
import com.leicx.guli.product.service.AttrAttrgroupRelationService;
import com.leicx.guli.product.service.AttrGroupService;
import com.leicx.guli.product.service.AttrService;
import com.leicx.guli.product.service.CategoryService;
import com.leicx.guli.product.vo.attr.AttrRespVo;
import com.leicx.guli.product.vo.attr.AttrVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Resource
    CategoryService categoryService;
    @Resource
    AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtil.copyProperties(attr, attrEntity);
        this.save(attrEntity);

        // 保存attr和attrGroup的关联关系
        if (Objects.equals(attr.getAttrType(), 1) && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationService.save(relationEntity);
        }
    }

    @Override
    public PageUtils baseList(Map<String, Object> params, Long catId, String attrType) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(catId) && catId != 0) {
            queryWrapper.eq("catelog_id", catId);
        }
        CommonPageQueryUtil.setKeyQuery(queryWrapper, params, "attr_id", "attr_name");
        // 规格参数和销售属性的搜索
        Integer attrTypeInt = "base".equalsIgnoreCase(attrType) ? 1 : 0;
        queryWrapper.eq(ParamConstant.ATTR_TYPE, attrTypeInt);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        // 设置所属分类和所属分组
        List<AttrRespVo> collect = page.getRecords().stream().map(item -> {
            AttrRespVo vo = BeanUtil.copyProperties(item, AttrRespVo.class);
            CategoryEntity categoryEntity = categoryService.getById(item.getCatelogId());
            if (categoryEntity != null) {
                vo.setCatelogName(categoryEntity.getName());
            }
            if (Objects.equals(item.getAttrType(), 1)) {
                AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getByAttrId(item.getAttrId());
                if (relationEntity != null && relationEntity.getAttrGroupId() != null) {
                    AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                    vo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
            return vo;
        }).collect(Collectors.toList());
        // 设置返回的list为vo
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = BeanUtil.copyProperties(attrEntity, AttrRespVo.class);
        // 设置所属分类和所属分组
        if (Objects.equals(attrEntity.getAttrType(), 1)) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationService.getByAttrId(attrId);
            if (relationEntity != null) {
                attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                if (groupEntity != null) {
                    attrRespVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
        }
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        Long[] pathByCatId = categoryService.getPathByCatId(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(pathByCatId);
        return attrRespVo;
    }

    @Override
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = BeanUtil.copyProperties(attr, AttrEntity.class);
        this.update(attrEntity, new UpdateWrapper<AttrEntity>().eq(ParamConstant.ATTR_ID, attrEntity.getAttrId()));
        if (Objects.equals(attrEntity.getAttrType(), 1)) {
            // 修改关联的attrGroup id
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            AttrAttrgroupRelationEntity byAttrId = attrAttrgroupRelationService.getByAttrId(attrEntity.getAttrId());
            if (byAttrId != null) {
                // 更新
                attrAttrgroupRelationService.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq(ParamConstant.ATTR_ID, attrEntity.getAttrId()));
            } else {
                // 新建
                attrAttrgroupRelationService.save(relationEntity);
            }
        }
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        if (CollUtil.isEmpty(attrIds)) {
            return new ArrayList<>();
        }
        List<AttrEntity> list = list(new QueryWrapper<AttrEntity>()
                .in(ParamConstant.ATTR_ID, attrIds)
                .eq("search_type", 1));
        return list.stream().map(AttrEntity::getAttrId).collect(Collectors.toList());
    }

}